<template>
  <div class="flex flex-col h-full">
    <BaseCard title="管理员管理">
      <div class="flex justify-between">
        <div>
          <el-button type="primary" @click="handleCommand('create')"
            >添加账户</el-button
          >
          <el-button
            plain
            @click="handleCommand('login_record')"
            class="text-[#376AF7] border-[#376AF7]"
            >登录记录</el-button
          >
        </div>
        <el-button
          type="primary"
          plain
          class="w-8 mr-[-16px]"
          :icon="RefreshRight"
          @click="getTableList"
        ></el-button>
      </div>
      <!-- <el-form
      ref="queryForm"
      :model="formState"
      class="flex items-center gap-x-6"
      inline
      @submit.prevent
    >
      <el-form-item prop="range" class="m-0" label="创建日期">
        <el-date-picker
          v-model="formState.range"
          class="w-60"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item prop="keywords" class="m-0">
        <el-input
          v-model="formState.keywords"
          class="w-60"
          placeholder="请输入用户ID/用户名/昵称/邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item class="m-0">
        <el-button type="primary" @click="handleSearchTable">查询</el-button>
        <el-button @click="handleResetQueryState">重置</el-button>
      </el-form-item>
    </el-form> -->
    </BaseCard>
    <div class="flex-1 mt-2 basic-page">
      <el-table
        v-loading="loading"
        class="basic-table"
        height="100%"
        :data="dataSource"
      >
        <el-table-column
          prop="username"
          show-overflow-tooltip
          label="用户名"
          width="148"
        >
          <template #default="{ row }">
            <span class="font-normal">{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="role"
          show-overflow-tooltip
          label="角色"
          width="126"
        >
          <template #default="{ row }">
            <span class="font-normal">{{ getRole(row.role) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="login_time"
          show-overflow-tooltip
          label="最近登陆时间"
          width="190"
        >
          <template #default="{ row }">
            <span class="font-normal">{{
              formatUnix(Number(row.login_time)) || '-'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="login_ip"
          show-overflow-tooltip
          label="最近登录IP"
          width="146"
        >
          <template #default="{ row }">
            <span class="font-normal">{{ row.login_ip || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="ip_addr"
          show-overflow-tooltip
          label="所在地"
          width="128"
        >
          <template #default="{ row }">
            <span class="font-normal">{{ row.ip_addr || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="184">
          <template #default="{ row }">
            <!-- mock 数据需要转换 所以除以1000 -->
            {{ formatUnix(Number(row.created_at)) }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="remark"
          label="备注"
          min-width="100"
        >
          <template #default="{ row }">
            <span class="font-normal">{{ row.remark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="status"
          label="状态"
          min-width="96"
        >
          <template #default="{ row }">
            <el-switch
              :model-value="row.status"
              inline-prompt
              active-text="开"
              inactive-text="关"
              :active-value="1"
              :inactive-value="2"
              @change="() => handleCommand('status', row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="{ row }">
            <div class="flex items-center justify-around">
              <el-link
                class="common-btn"
                :underline="false"
                type="primary"
                @click="handleCommand('reset', row)"
                >重置密码</el-link
              >
              <el-link
                class="common-btn"
                :underline="false"
                type="primary"
                @click="handleCommand('editor_dialog', row)"
                >编辑</el-link
              >
              <el-link
                class="common-btn"
                :underline="false"
                type="danger"
                @click="handleCommand('delete', row)"
                >删除</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <BasicPagination
        ref="paginationRef"
        :total="total"
        :disabled="loading"
        @change="getTableList"
      ></BasicPagination>
    </div>
  </div>
  <!-- 编辑账户 -->
  <EditorDialog
    v-model:visible="editorState.visible"
    :record="editorState.record"
    @close-dialog="() => (editorState.visible = false)"
    @reload="getTableList"
  />
  <login-record
    v-model:visible="recordState.recordVisible"
    v-model:loading="recordState.loading"
  />
</template>

<script setup lang="ts">
import { RefreshRight } from '@element-plus/icons-vue'
import LoginRecord from './dialogs/LoginRecord.vue'
import { ElMessageBox, ElNotification } from 'element-plus'
import BaseCard from '@/components/base-card'
import { get, isFunction } from 'lodash-es'
import { ROLE_DATA } from './state'

import type { UserModel } from '@/apis/model/user'
import { formatUnix } from '@/utils'

import EditorDialog from './dialogs/EditorDialog.vue'

interface FormState {
  // range?: [number, number]
  offset: number
  limit: number
}
const router = useRouter()
const getRole = computed(() => (role: number) => ROLE_DATA[role] || '-')
const formState = reactive<FormState>({
  offset: 0,
  limit: 20
})

const editorState = reactive<CommonDialog<UserModel>>({
  visible: false,
  record: {} as UserModel,
  loading: false
})

const paginationRef = ref()
const loading = ref<boolean>(false)
const dataSource = ref<UserModel[]>([])
const total = ref(0)
const recordState = reactive({
  recordVisible: false,
  loading: false
})
const getTableList = () => {
  loading.value = true
  const query = {
    ...formState
  }
  userListApi(query)
    .then(res => {
      dataSource.value = res?.list ?? []
      total.value = +res?.total ?? 0
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 200)
    })
}

type ICommand =
  | 'reset'
  | 'edit'
  | 'delete'
  | 'create'
  | 'login_record'
  | 'editor_dialog'
  | 'status'
const handleCommand = (command: ICommand, record?: UserModel) => {
  const actions: Record<ICommand, () => void> = {
    create: (): void => {
      editorState.record = null
      editorState.visible = true
      editorState.loading = false
    },
    edit: (): void => {
      router.push({
        name: 'AdminEditorExample',
        params: record?.id ? { id: record.id } : {}
      })
    },
    reset: (): void => {
      ElMessageBox.confirm(
        '确定将该管理员密码重置为abcd.1234吗？',
        '重置密码',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'basic-message-box'
        }
      )
        .then(() => {
          reset_pwd({ id: record?.id as string }).then(() => {
            ElNotification.success({
              title: '成功',
              message: '重置成功'
            })
            getTableList()
          })
        })
        .catch(() => {})
    },
    delete: (): void => {
      ElMessageBox.confirm('确定要删除该用户吗？', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'basic-message-box'
      })
        .then(() => {
          delete_user({ id: record?.id as string }).then(() => {
            ElNotification.success({
              title: '成功',
              message: '删除成功'
            })
            getTableList()
          })
        })
        .catch(() => {})
    },
    login_record: (): void => {
      recordState.recordVisible = true
    },
    editor_dialog: (): void => {
      editorState.record = record
      editorState.visible = true
      editorState.loading = false
    },
    status: (): void => {
      const msg = record?.status === 1 ? '确认禁用用户？' : '确认启用用户？'
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'basic-message-box'
      })
        .then(() => {
          loading.value = true
          edit_user({
            id: record?.id as string,
            status: record?.status === 1 ? 2 : 1
          })
            .then(() => {
              ElNotification.success({
                title: '成功',
                message: record?.status === 1 ? '禁用成功' : '启用成功'
              })
              getTableList()
            })
            .finally(() => {
              loading.value = false
            })
        })
        .catch(() => {
          // 取消按钮
          // getTableList()
        })
    }
  }
  if (isFunction(get(actions, command))) {
    actions[command]()
  }
}

onMounted(getTableList)
</script>

<style lang="scss" scoped></style>
